package com.zlq.add.Thread;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 使用ReentrantLock实现同步
 * lock()方法：上锁
 * unlock()方法：释放锁
 */

public class Test {
    public static void main(String[] args) throws InterruptedException{
        MyCondition myCondition = new MyCondition();
        Thread thread1 = new Thread(myCondition, "线程1");
        thread1.start();
        Thread.sleep(3000);
        myCondition.signal();

    }
}

class MyCondition implements Runnable{
    private Lock lock = new ReentrantLock();
    public Condition condition = lock.newCondition();
    @Override
    public void run() {
        try {
            //上锁
            lock.lock();
            System.out.println("当前线程名："+Thread.currentThread().getName()+"开始等待时间："+System.currentTimeMillis());
            //线程等待
            condition.await();      //wait
            System.out.println("我陷入了等待...");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            //释放锁
            lock.unlock();
            System.out.println("锁释放了！...");
        }

    }

    //通知方法信号
    public void signal(){
        try {
            lock.lock();
            System.out.println("结束等待时间："+System.currentTimeMillis());
            //通知等待线程
            condition.signal();     //notify
        } finally {
            lock.unlock();
        }
    }
}
